/*************************************************************************
	> File Name: MyDB.cc
	> Author: likang
	> Mail:  
	> Created Time: 2015年01月11日 星期日 00时15分14秒
 ************************************************************************/

#include<iostream>
#include<cstdlib>
#include"MyDB.h"
#include"../vector_serialization.h"
#include<sstream>
using namespace std;

MyDB::MyDB() {
	connection = mysql_init(NULL);
	if (connection == NULL) {
		cout << "Error:" << mysql_error(connection);
		exit(1);
	}
}

MyDB::~MyDB() {
	if (connection != NULL) {
		mysql_close(connection);
	}
}

bool MyDB::initDB(string host, string user, string pwd, string db_name) {
	connection = mysql_real_connect(connection, host.c_str(), user.c_str(), pwd.c_str(), db_name.c_str(), 0, NULL, 0);
	if (connection == NULL) {
		cout << "ERROR:" << mysql_error(connection);
		exit(1);
	}
	return true;
}

bool MyDB::execSQL(string sql, string &stresult) {
	mysql_query(connection,"set names 'utf8'");
	//cout << "sql:" << sql << endl;
	if (mysql_query(connection, sql.c_str())) {
		cout << "sql:" << sql.c_str() << endl;
		cout << "Query Error:" << mysql_error(connection);
		string err = mysql_error(connection);
		stresult = "Query Error" + err;
	}
	else {
		//Retrieves a complete result set to the client
		result = mysql_store_result(connection);
		if (result) {
			vector<string> revec;
			while (true){
			//fetches the next row from the result set
				row = mysql_fetch_row(result);
				if (row == NULL) {
					cout << "row is null" << endl;
					break;
				}
				for (int j = 0; j < mysql_num_fields(result); ++j) {
					cout << row[j] << " ";
					revec.push_back(row[j]);
				}
				revec.push_back("##");
				cout << endl;
			}
			for (vector<string>::iterator it = revec.begin(); it != revec.end(); ++it)
				cout << "**" << *it;
			if (revec.size() == 0) {
				cout << "empty" << endl;
				revec.push_back("empty");
			}
				
			stresult = save(revec);
			mysql_free_result(result);
		}
		else {
			stringstream ss;
			//return the number of columns for the most recent query on the connection
			if (mysql_field_count(connection) == 0) {
				unsigned int num_rows = mysql_affected_rows(connection);
				cout << "affected " << num_rows << " rows" << endl;
				ss << num_rows;
				string a;
				ss >> a;
				stresult = "affected " + a + " row";
				cout << "stresult:" << stresult << endl;
			}
			else {
				cout << "Error:" << mysql_error(connection);
				ss << "Error:" << mysql_error(connection);
				ss >> stresult;
				exit(1);
			}
		}
	}
	return true;
}

